package com.atguigu.gmall.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.UUID;

public class JwtUtils {

    private static final String SECRET_KEY = "ATGUIGU";

    /**
     * 生成JWT方式
     * @param subject
     * @return
     */
    public static String generateToken(String subject) {
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime expirationTime = currentTime.plusMinutes(30);

        Date issuedAt = Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant());
        Date expiresAt = Date.from(expirationTime.atZone(ZoneId.systemDefault()).toInstant());

        return Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(issuedAt)
                .setExpiration(expiresAt)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    /**
     * 验证JWT 是否正确
     * @param token
     * @return
     */
    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从JWT 字符串中获取数据
     * @param token
     * @return
     */
    public static String getUUIDFromToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
        return claims.getSubject();
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        String token = generateToken(UUID.randomUUID().toString());
        System.out.println(token);
        System.out.println(validateToken(token));
        System.out.println(getUUIDFromToken(token));

    }
}
